﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;
using System.Text;
using System.Drawing;

namespace MusaDor.Publisher
{
    public partial class AddPlace : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public int returnValue { get; set; }

        protected void Send_Click(object sender, EventArgs e)
        {
            Boolean Approved = false;
            String AddedBy = User.Identity.Name;
            String connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            String PreviewPath = Server.MapPath("~/Images/Sections/PreviewImages/");
            String FullPath = Server.MapPath("~/Images/Sections/FullImages/");
            Boolean PreviewFileOK = false;
            Boolean FullFileOK = false;
            Boolean PreviewImageOK = false;
            Boolean FullImageOk = false;
            Boolean PreviewImageResolution = false;
            Boolean FullImageResolution = false;

            if (IsPostBack)
            {
                if (PreviewImageUpload.HasFile)
                {
                    String fileExtension =
                        System.IO.Path.GetExtension(PreviewImageUpload.FileName).ToLower();
                    String[] allowedExtensions = { ".png" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        try
                        {
                            Bitmap previewimage = new Bitmap(PreviewImageUpload.FileContent);

                            if ((previewimage.Size.Height == 200) && (previewimage.Size.Width == 200))
                            {
                                if (fileExtension == allowedExtensions[i])
                                {
                                    PreviewFileOK = true;
                                    PreviewImageResolution = true;
                                }
                            }
                        }
                        catch
                        {
                            PreviewImageUploadStatus.Text = "Error";
                        }

                    }
                }

                if (PreviewFileOK)
                {
                    try
                    {
                        PreviewImageOK = true;
                    }
                    catch (Exception exp)
                    {
                        PreviewImageUploadStatus.Text = "Error";
                    }
                }
                else
                {
                    if (PreviewImageResolution)
                    {
                        PreviewImageUploadStatus.Text = "Size of miniature must be 200х200 px.";
                    }
                    else
                    {
                        PreviewImageUploadStatus.Text = "Error";
                    }
                }
            }

            if (IsPostBack)
            {
                if (FullImageUpload.HasFile)
                {
                    String fileExtension =
                        System.IO.Path.GetExtension(FullImageUpload.FileName).ToLower();
                    String[] allowedExtensions = { ".png" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        try
                        {
                            Bitmap fullimage = new Bitmap(FullImageUpload.FileContent);

                            if ((fullimage.Size.Height == 600) && (fullimage.Size.Width == 800))
                            {
                                if (fileExtension == allowedExtensions[i])
                                {
                                    FullFileOK = true;
                                    FullImageResolution = true;
                                }
                            }
                        }
                        catch
                        {
                            FullImageUploadStatus.Text = "Error";
                        }
                    }
                }

                if (FullFileOK)
                {
                    try
                    {
                        FullImageOk = true;
                    }
                    catch (Exception exf)
                    {
                        FullImageUploadStatus.Text = "Error";
                    }
                }
                else
                {
                    if (FullImageResolution)
                    {
                        FullImageUploadStatus.Text = "Size of full image must be 800х600 px.";
                    }
                    else
                    {
                        FullImageUploadStatus.Text = "Error";
                    }

                }
            }


            if (PreviewImageOK == true)
            {
                if (FullImageOk == true)
                {
                    Guid NewPreviewImageFileName = Guid.NewGuid();
                    String fileExtension = Path.GetExtension(PreviewImageUpload.FileName);
                    String fullPreviewImageFileName = PreviewPath + NewPreviewImageFileName + fileExtension;
                    String ShortPreviewImageFileName = NewPreviewImageFileName + fileExtension;
                    PreviewImageUpload.PostedFile.SaveAs(fullPreviewImageFileName);

                    Guid NewFullImageFileName = Guid.NewGuid();
                    String FullImagefileExtension = Path.GetExtension(FullImageUpload.FileName);
                    String FullFullImageFileName = FullPath + NewFullImageFileName + fileExtension;
                    String ShortFullImageFileName = NewFullImageFileName + fileExtension;
                    FullImageUpload.PostedFile.SaveAs(FullFullImageFileName);

                    String latitudeValue = latitude.Text;
                    String longitudeValue = longitude.Text;
                    String descriptionValue = description.Text;
                    Guid MapName = Guid.NewGuid();
                    String StringMapName = Convert.ToString(MapName);

                    CreateMap(latitudeValue, longitudeValue, descriptionValue, StringMapName);

                    int CategoryID = 7;

                    using (SqlConnection conn = new SqlConnection(connStr))
                    {

                        string sql = "INSERT INTO md_Articles ([Title],[Body],[ImagePreview],[ImageFull],[Approved],[FileName],[AddedBy],[CategoryID]) VALUES " + "(@Title,@Body,@ImagePreview,@ImageFull,@Approved,@FileName,@AddedBy,@CategoryID)";

                        using (SqlCommand cmd = new SqlCommand(sql, conn))
                        {

                            SqlParameter[] prms = new SqlParameter[8];
                            prms[0] = new SqlParameter("@Title", SqlDbType.NVarChar, 256);
                            prms[0].Value = TextBoxTitle.Text.Trim();
                            prms[1] = new SqlParameter("@Approved", SqlDbType.Bit);
                            prms[1].Value = Approved;
                            prms[2] = new SqlParameter("@Body", SqlDbType.NText);
                            prms[2].Value = Article.Text.Trim();
                            prms[3] = new SqlParameter("@ImagePreview", SqlDbType.NVarChar, 256);
                            prms[3].Value = ShortPreviewImageFileName;
                            prms[4] = new SqlParameter("@ImageFull", SqlDbType.NVarChar, 256);
                            prms[4].Value = ShortFullImageFileName;
                            prms[5] = new SqlParameter("@FileName", SqlDbType.NVarChar, 256);
                            prms[5].Value = StringMapName;
                            prms[6] = new SqlParameter("@AddedBy", SqlDbType.NVarChar, 256);
                            prms[6].Value = AddedBy;
                            prms[7] = new SqlParameter("@CategoryID", SqlDbType.Int, 4);
                            prms[7].Value = CategoryID;
                            cmd.Parameters.AddRange(prms);
                            conn.Open();
                            returnValue = cmd.ExecuteNonQuery();
                            conn.Close();

                            latitude.Text = "";
                            longitude.Text = "";
                            TextBoxTitle.Text = "";
                            Article.Text = "";

                        }
                    }
                }


            }
        }

        protected void CreateMap(string latitude, string longitude, string description, string MapName)
        {
            /*Get your keys for maps on developer.here.com*/

            string Map;
            Map = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
            "<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
                "<head>" +
                    "<title></title>" +
                    "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=7; IE=EmulateIE9; IE=EmulateIE10;\"/>" +
                    "<meta name=\"viewport\" content=\"initial-scale=1.0, maximum-scale=1.0, user-scalable=no\"/>" +
                    "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://developer.here.com/apiexplorer/examples/templates/js/exampleHelpers.css\"/>" +
		            "<link rel=\"stylesheet\" type=\"text/css\" href=\"Maps.Css\"/>" +
                    "<script type=\"text/javascript\" charset=\"UTF-8\" src=\"http://api.maps.nokia.com/2.2.4/jsl.js?with=all\"></script>" +
                    "<script type=\"text/javascript\" charset=\"UTF-8\" src=\"http://developer.here.com/apiexplorer/examples/templates/js/exampleHelpers.js\"></script>" +
                "</head>" +
                "<body>" +
                    "<div id=\"mapContainer\"></div>" +
                    "<div id=\"uiContainer\"></div>" +
                    "<script type=\"text/javascript\" id=\"exampleJsSource\">" +
                    " " +
                        "nokia.Settings.set(\"appId\", \"fFnWUfbSd582mXiMTNwP\");" +
                        " " +
                        "nokia.Settings.set(\"authenticationToken\", \"BTXKbvLicFPKJKTqDYPGXg\");" +
                        " " +
                        "nokia.Settings.set(\"defaultLanguage\", \"ru-RU\");" +
                        " " +
                        "var mapContainer = document.getElementById(\"mapContainer\");" +
                        " " +
                        "var infoBubbles = new nokia.maps.map.component.InfoBubbles();" +
                        " " +
                        "var map = new nokia.maps.map.Display(mapContainer, {" +
                        " " +
                            "center: [" + latitude + " , " + longitude + "]," +
                            " " +
                            "zoomLevel: 15," +
                            " " +
                            "components: [infoBubbles," +
                            " " +
                            "new nokia.maps.map.component.ZoomBar()," +
                            " " +
                            "new nokia.maps.map.component.TypeSelector()," +
                            " " +
                            "new nokia.maps.map.component.Behavior()" +
                            " " +
                            "]" +
                            " " +
                        "});" +
                        " " +
                        "var standardMarker = new nokia.maps.map.StandardMarker(map.center);" +
                        " " +
                        "var TOUCH = nokia.maps.dom.Page.browser.touch," +
                        " " +
                "CLICK = TOUCH ? \"tap\" : \"click\";" +
                " " +
                        "standardMarker.addListener(" +
                        " " +
                "CLICK," +
                " " +
                "function (evt) {" +
                " " +
                    "infoBubbles.openBubble(\"" + description + "\", standardMarker.coordinate);" +
                    " " +
                "}" +
                " " +
            ");" +
            " " +
                        "map.objects.add(standardMarker);" +
                        " " +
                    "</script>" +
                "</body>" +
            "</html>";

            using (StreamWriter w = new StreamWriter(Server.MapPath("~/maps/" + MapName + ".html"), true, Encoding.UTF8))
            {
                w.WriteLine(Map);
            }
 
    }
    }
}